package com.example.thirdhomework

import android.os.Bundle
import android.os.SystemClock
import android.widget.Button
import android.widget.Chronometer
import androidx.appcompat.app.AppCompatActivity

class FifthActivity : AppCompatActivity() {
    private lateinit var chronometer: Chronometer
    private var lastPause: Long = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fifth)

        chronometer = findViewById(R.id.chronometer)
        val startButton: Button = findViewById(R.id.button_start)
        val stopButton: Button = findViewById(R.id.button_stop)
        val restartButton: Button = findViewById(R.id.button_restart)

        startButton.setOnClickListener {
            if (lastPause != 0L) {
                chronometer.base = chronometer.base + SystemClock.elapsedRealtime() - lastPause
            } else {
                chronometer.base = SystemClock.elapsedRealtime()
            }
            chronometer.start()
        }

        stopButton.setOnClickListener {
            lastPause = SystemClock.elapsedRealtime()
            chronometer.stop()
        }

        restartButton.setOnClickListener {
            chronometer.base = SystemClock.elapsedRealtime()
            lastPause = 0
            chronometer.start()
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putLong("chronometer_base", chronometer.base)
        outState.putLong("last_pause", lastPause)
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        chronometer.base = savedInstanceState.getLong("chronometer_base")
        lastPause = savedInstanceState.getLong("last_pause")
        if (lastPause == 0L) {
            chronometer.start()
        }
    }
}